package com.zmcn.fileTransfer.fw.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 基于口令的对称加解密
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
public class SecurityUtil3 {
	/*
	 * 基于口令的对称加密
	 */
	public static String encrypt(String sou) throws Exception {
		// 实例化工具
		Cipher cipher2 = Cipher.getInstance("PBEWithMD5AndDES");

		// 使用该工具将基于密码的形式生成Key
		SecretKey key2 = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec(PWD.toCharArray()));
		PBEParameterSpec parameterspec = new PBEParameterSpec(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000);

		// 初始化加密操作，同时传递加密的算法
		cipher2.init(Cipher.ENCRYPT_MODE, key2, parameterspec);

		// 将要加密的数据传递进去，返回加密后的数据
		byte[] results = cipher2.doFinal(sou.getBytes());

		// 合成字符串
		BASE64Encoder encoder = new BASE64Encoder();
		String encodedStr = new String(encoder.encodeBuffer(results));
		return encodedStr.trim();
	}

	/*
	 * 基于口令的对称解密
	 */
	public static String decrypt(String sou) throws Exception {
		BASE64Decoder dec = new BASE64Decoder();
		byte[] src = dec.decodeBuffer(sou);
		Cipher cipher2 = Cipher.getInstance("PBEWithMD5AndDES");
		SecretKey key2 = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec(PWD.toCharArray()));
		PBEParameterSpec parameterspec = new PBEParameterSpec(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000);
		cipher2.init(Cipher.DECRYPT_MODE, key2, parameterspec);
		byte[] result = cipher2.doFinal(src);
		return new String(result);
	}
	
	private static final String PWD = "20120803oyjd@163.com";

}
